<?php

namespace app\api\controller;

use ba\Tree;
use Throwable;
use think\facade\Db;
use think\facade\Config;
use app\common\controller\Frontend;
use app\common\library\token\TokenExpirationException;

class Index extends Frontend
{
    protected array $noNeedLogin = ['index'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 前台和会员中心的初始化请求
     * @throws Throwable
     */
    public function index(): void
    {

//
//        $url = 'https://id.kuaishou.com/pass/kuaishou/email/ks/loginAccount/v2';
//
//        // 获取当前时间戳（13位，单位：毫秒）
//        $timestamp = (int)(microtime(true) * 1000);
//
//        $headers = [
//            'Accept: */*',
//            'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8',
//            'Cache-Control: no-cache',
//            'Connection: keep-alive',
//            'Content-Type: application/x-www-form-urlencoded',
//            'Origin: https://niu.e.kuaishou.com',
//            'Pragma: no-cache',
//            'Referer: https://niu.e.kuaishou.com/',
//            'Sec-Fetch-Dest: empty',
//            'Sec-Fetch-Mode: cors',
//            'Sec-Fetch-Site: same-site',
//            'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36',
//            'sec-ch-ua: "Google Chrome";v="135", "Not-A.Brand";v="8", "Chromium";v="135"',
//            'sec-ch-ua-mobile: ?0',
//            'sec-ch-ua-platform: "macOS"',
//            'yzzh-nc: k4zjx3nyS5',
//            'yzzh-tsp: ' . $timestamp,
//            'yzzh-vs: version0',
//        ];
//
//        // 快手要求携带的 Cookie（模拟浏览器身份）
//        $cookies = 'weblogger_did=web_2453005089B5225E; _did=web_129907553E29245E; did=web_907efccfab9ac15447306122d18c11a26373; bUserId=1000445132328';
//
//        // 构造请求体（原始就是 application/x-www-form-urlencoded 结构）
//        $postFields = http_build_query([
//            'sid' => 'kuaishou.ad.esp',
//            'captchaToken' => '',
//            'encryptHeaders' => '',
//            'password' => '137d537f41d59849e4379c15d6e49f0e356f80f626d28b01ffaa0d8b0879add1e9572f54d8274d411687196f0e0fb43ea0d985c8b51283f90bfaf2b7685c1a58299078cc343698f34358f8614e993400f66f2d2cc38047c784cbad3e7a425fdc3be0f563eed7ed95338bf03d15069990e5dc6d003f28abd69ff8f9162167c406ae80cac9673e41ec58ddef2ddbf799dc370d3a778962545831ddab45befdce9a21f69b0d26ae957862668879ca05dc62405dcd2d28de4a39fda6ee70cbd3ecd8d15a8464e516fde4adfb4fba4836608666e667c8a17e8ee5f16d6860e225be7cc5eb205ed9619150fc081615e681344d4aebc5ab0488cb7646793bc72c414507',
//            'ignorePwd' => false,
//            'account' => '4e1006d1a493a6bbf287de5f5da48c78a1986d51e13560d1b0fda4376f6cd6d2793844ac9c3dbef58031110a3f4012da5f8c833d4b42d3a44073c914c51c2868190646e05e5102a822c8fed6ed9afa938ac52e8bcdbe88a8849d9520cddbe8ba3d534c8ca7db2fd9cfc9bbca13be781dd800556e8f3da7ec94a3567a0d23a3858eb2a65618cd865eaecc4aa62ec067a8557453928db4198379f784c976c74024aa377adba8ae6b87dcc611ebd3be66935b65d7c450ac92c35078c064364a06d677a100f60ec6a5abfe35071b59af4a8f3ae10e370cc13afdf038630ba9a40098f9a8a2e6fd1cd5b88f99c369e059de546da02264b4e93e636522e3bdfbdbee02',
//            'ignoreAccount' => false,
//            'channelType' => 'UNKNOWN',
//        ]);
//
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_POST, true);
//        curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_TIMEOUT, 20);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//        curl_setopt($ch, CURLOPT_COOKIE, $cookies);
//
//        $response = curl_exec($ch);
//        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//        $curlError = curl_error($ch);
//        curl_close($ch);
//
//        // 打印结果
//        echo "HTTP 状态码: {$httpcode}\n";
//        if ($curlError) {
//            echo "CURL 错误: {$curlError}\n";
//        } else {
//            echo "响应内容:\n" . $response;
//        }
//        die;

        $menus = [];
        if ($this->auth->isLogin()) {
            $rules     = [];
            $userMenus = $this->auth->getMenus();

            // 首页加载的规则，验权，但过滤掉会员中心菜单
            foreach ($userMenus as $item) {
                if ($item['type'] == 'menu_dir') {
                    $menus[] = $item;
                } elseif ($item['type'] != 'menu') {
                    $rules[] = $item;
                }
            }
            $rules = array_values($rules);
        } else {
            // 若是从前台会员中心内发出的请求，要求必须登录，否则会员中心异常
            $requiredLogin = $this->request->get('requiredLogin/b', false);
            if ($requiredLogin) {

                // 触发可能的 token 过期异常
                try {
                    $token = get_auth_token(['ba', 'user', 'token']);
                    $this->auth->init($token);
                } catch (TokenExpirationException) {
                    $this->error(__('Token expiration'), [], 409);
                }

                $this->error(__('Please login first'), [
                    'type' => $this->auth::NEED_LOGIN
                ], $this->auth::LOGIN_RESPONSE_CODE);
            }

            $rules = Db::name('user_rule')
                ->where('status', 1)
                ->where('no_login_valid', 1)
                ->where('type', 'in', ['route', 'nav', 'button'])
                ->order('weigh', 'desc')
                ->select()
                ->toArray();
            $rules = Tree::instance()->assembleChild($rules);
        }

        $this->success('', [
            'site'             => [
                'siteName'     => get_sys_config('site_name'),
                'version'      => get_sys_config('version'),
                'cdnUrl'       => full_url(),
                'upload'       => keys_to_camel_case(get_upload_config(), ['max_size', 'save_name', 'allowed_suffixes', 'allowed_mime_types']),
                'recordNumber' => get_sys_config('record_number'),
                'cdnUrlParams' => Config::get('buildadmin.cdn_url_params'),
            ],
            'openMemberCenter' => Config::get('buildadmin.open_member_center'),
            'userInfo'         => $this->auth->getUserInfo(),
            'rules'            => $rules,
            'menus'            => $menus,
        ]);
    }
}
